package com.browsesoft.oa;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Hashtable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.browsesoft.PropertiesService;
import com.browsesoft.baseadapter.BlobEntity;
import com.browsesoft.baseadapter.BlobEntityFactory;
import com.browsesoft.baseadapter.SimpleEntity;
import com.browsesoft.util.StreamHelper;

/**
 * 发文送签流程中的附件所需要的一个实体。这个实体负责取出属于当前活动或者叫做流程的所有附件。 同时，这也是一个model，负责把上传的附件保存到正确的地方。
 * <p>
 * Copyright: Copyright (c) 2004
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author not attributable
 * @version 1.0
 */
public class AttackmentEntity extends SimpleEntity {
	/**
	 * 
	 */
	private static final long serialVersionUID = -1404439164923599184L;

	BSMIMEParser parser;

	public AttackmentEntity() {
	}

	public AttackmentEntity(Hashtable attr) {
		super(attr);
	}

	public void init(HttpServletRequest request) throws Exception {
		super.init(request);
	}

	/**
	 * 页面服务
	 * 
	 * @throws Exception
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		super.service(request, response);
		if (action != null && action.equals("confirm")) {
			parser = (BSMIMEParser) request.getAttribute("parser");
			if (parser != null) {
				this.attributes.put("realname", parser.getRealName());
				this.attributes.put("blob_id", parser.getBlobID());
				String str = request.getParameter("illustrate");
				this.attributes.put("illustrate", str);
			}
		}
	}

	public String getFilePathName() throws Exception {
		String path = PropertiesService.getProperty("attackment", "path");
		String id = (String) this.attributes.get("blob_id");
		String filename = getFileRealName();
		int pos = filename.lastIndexOf(".");
		String savename = id;
		if (pos != -1) {
			savename += filename.substring(pos, filename.length());
		}
		return path + savename;
	}

	public String getFileSaveName() {
		return (String) this.attributes.get("savename");
	}

	public String getFileRealName() {
		return (String) this.attributes.get("realname");
	}

	public void delete() throws Exception {
		// 调用父类的delete方法，让其删除数据库中对应的记录。
		super.delete();
		try {
			// 得到这些文件的路径
			String path = PropertiesService.getProperty("attackment", "path");
			path = path + this.attributes.get("savename");
			File file = new File(path);
			file.delete();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void save(InputStream is, String fileName) throws Exception {

		BlobEntity obe = BlobEntityFactory.getInstance().newBlobEntity();
		OutputStream os = obe.getOutputStream();
		this.getAttributes().put("realname", fileName);
		this.getAttributes().put("blob_id", obe.getID());
		// 调用流工具类，把输入流内容给输出流
		StreamHelper.transformStream(is, os);
		obe.save();
		os.close();
		is.close();
	}
}
